import { useEffect, useRef, useCallback } from 'react';
/**
 * 防抖hook -多次执行变为最后一次执行
 * 单位时间内事件触发会被重置，避免事件被误触发多次，触发高频事件，n秒内事件只会执行一次，如果n秒内再次触发，则会重新计算时间
 * @param fn 需要执行的函数
 * @param delay 延迟时间
 * @param immediate 是否立即执行
 */
var useDebounce = function useDebounce(fn, options) {
  var _ref = options || {},
    _ref$delay = _ref.delay,
    delay = _ref$delay === void 0 ? 500 : _ref$delay,
    immediate = _ref.immediate;
  var fnRef = useRef(fn);
  var timerRef = useRef(null);
  useEffect(function () {
    fnRef.current = fn;
  }, [fn]);
  var execute = useCallback(function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (timerRef.current) {
      cancel();
    }
    if (immediate) {
      fnRef.current.apply(fnRef, args);
    } else {
      timerRef.current = setTimeout(function () {
        fnRef.current.apply(fnRef, args);
        timerRef.current = null;
      }, delay);
    }
  }, []);
  var cancel = useCallback(function () {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  }, []);
  useEffect(function () {
    return cancel;
  }, [cancel]);
  return {
    execute: execute,
    cancel: cancel
  };
};
export default useDebounce;